<?php
require_once("AbstractService.php");
require_once("services/PollObservingService.php");

class ServiceDispathcer{
	static public function makeClassName($serviceId){
		return ucfirst($serviceId)."Service";
	}
	static public function makeServiceFileName($className){
		return "services/$className.php";
	}
	static public function makeResponse($serviceId, $requestId, $returnCode, $returnMsg, $responseParams){
		$response = array();
		$response["serviceId"] = $serviceId;
		$response["requestId"] = $requestId;
		$response["returnCode"] = $returnCode;
		$response["returnMsg"] = $returnMsg;
		if ($responseParams != null)
			$response["params"] = $responseParams;
		return $response;
	}
 	static public function doService($serviceId, $requestId, $clientId, $params){
 		if ($serviceId == null){
 			//TODO error load class
 			Logger::error("serviceId is empty.");
 			return;
 		}
 		$className = ServiceDispathcer::makeClassName($serviceId);
 		$serviceFileName = ServiceDispathcer::makeServiceFileName($className);
 		$responseList = array();
 		
 		if (file_exists("classes/".$serviceFileName)){

 			require_once($serviceFileName);
 			if (!class_exists($className, false)){
				Logger::error("serviceId[$serviceId] Class cannot load. [$serviceFileName]");
				return;
 			}
 			
 			$service = new $className($params);
 			try {
 				$responseParams = $service->doService($requestId, $params);
 				$response = ServiceDispathcer::makeResponse($serviceId, $requestId, "0000", "", $responseParams);
 			} catch (Exception $e) {
 				$response = ServiceDispathcer::makeResponse($serviceId, $requestId, $e->getCode(), $e->getMessage() , null);
 			}
 			array_push($responseList, $response);
 			
 			if ($serviceId == "pollObserving"){
 				
 				$observeringResponses = $service->getObservingResponses($clientId, $params);
 			}
 			else{
 				$pollObservingService = new PollObservingService();
 				$observeringResponses = $pollObservingService->getObservingResponses($clientId, $params);
 			}
 			if ($observeringResponses != null)
 				$responseList = array_merge($responseList, $observeringResponses);
 				
 			$responseData = array();
 			$responseData["responseList"] = $responseList;
 			return $responseData;
 		}
 		else{
 			//TODO error load class
 			Logger::error("serviceId[$serviceId] is not existed.($serviceFileName)");
 			return;
 		}
 	}
}
?>